package com.rp.system.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.raptor.pagination.Page2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageData;
import com.rp.controller.RpController;
import com.rp.system.po.Authority;
import com.rp.system.service.AuthorityService;

@Controller
@RequestMapping("/rp/system/authMng/")
public class AuthorityController extends RpController {

	@Autowired
	private AuthorityService authorityService;
	
	@RequestMapping("showAuthGrid")
	public ModelAndView showAuthGrid(){
		model.put("webpageTitle", "权限管理");
		return forward("/rp/system/authMng/authGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getAuths")
	public PageData getAuths(Authority auth){
		Page2 page = authorityService.getAuthorityDao().getAuthoritiesByPage(pageParam, auth);
		return new PageData(page);
	}
	
	@ResponseBody
	@RequestMapping("getWaitAllotAuths")
	public PageData getWaitAllotAuths(String roleId){
		Page2 page = authorityService.getAuthorityDao().getAuthoritiesByPage(pageParam, roleId);
		return new PageData(page);
	}
	
	@ResponseBody
	@RequestMapping("getHasAuths")
	public List<Authority> getHasAuths(String roleId){
		List<Authority> auths = null;
		try {
			auths = authorityService.getAuthorityDao().getAuthoritiesByRoleId(roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return auths; 
	}
	
	@ResponseBody
	@RequestMapping("saveAuths")
	public String saveAuths(String data){
		try {
			List<Authority> auths = JsonUtil.jsonToList(data, "com.rp.system.po.Authority");
			for (Authority auth : auths) {
				if(auth.getId() == null){
					authorityService.saveAuthority(auth);
				}else{
					authorityService.updateAuthority(auth);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteAuths")
	public String deleteAuths(String data){
		try {
			List<Authority> auths = JsonUtil.jsonToList(data, "com.rp.system.po.Authority");
			for (Authority authority : auths) {
				authorityService.deleteAuthority(authority.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
}
